package BlogMybatis.blog.service.impl;


import BlogMybatis.blog.service.QQMailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
public class QQMailServiceImpl implements QQMailService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender mailSender;
    //发送者QQ
    @Value("${mail.fromMail.addr}")
    private String from;


    /**
     * 发送文本邮件
     * @param to 定义发送给谁
     * @param subject 邮件标题
     * @param content 邮件内容模板
     */
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        logger.info("发送文本邮件开始：{},{},{}", to, subject, content);
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setText(content);
        message.setTo(to);
        message.setSubject(subject);
        try {
            mailSender.send(message);
            logger.info("简单文本已经发送。");
        } catch (Exception e) {
            logger.error("发送文本邮件时发生异常！", e);
        }
    }

    /**
     * 发送html邮件
     * @param to 定义发送给谁
     * @param subject 邮件标题
     * @param content 邮件内容模板
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        logger.info("发送HTML邮件开始：{},{}",to,subject);
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            messageHelper.setText(content,true);
            mailSender.send(message);
            logger.info("html邮件发送成功");
        }catch (MessagingException e) {
            logger.error("发送html邮件时发生异常！", e);
        }
    }
}
